package com.example.mybatisstudy1.redis;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {

    private final String id; // 缓存 ID（通常是 Mapper 的命名空间）
    private static RedisTemplate<String, Object> redisTemplate; // 静态变量，用于存储 RedisTempla
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public RedisCache(String id) {
        this.id = id;
        this.redisTemplate = getRedisTemplate();
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {

        redisTemplate.opsForValue().set(key.toString(), value);
    }

    @Override
    public Object getObject(Object key) {
        return redisTemplate.opsForValue().get(key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        System.out.println("===============removeObject");
        redisTemplate.delete(key.toString());
        return null;
    }

    @Override
    public void clear() {
        System.out.println("===============clear");
        redisTemplate.delete("*:"+id + ":*");
    }

    @Override
    public int getSize() {
        return redisTemplate.keys(id + ":*").size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate<String, Object> getRedisTemplate() {

        return redisTemplate;
    }
    // 静态方法，用于设置 RedisTemplate
    public static void setRedisTemplate(RedisTemplate<String, Object> template) {
        redisTemplate = template;
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
    }
}